from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from utils.logger import Logger
from utils.constants import ErrorCode
from app.core.config import settings
from .middleware import auth_middleware, rate_limiter_middleware
from .routers.search import search_router
from .routers.status import status_router
from .async_routers import async_router

# 初始化日志
logger = Logger.get_logger(agent_name="api_gateway")

# 创建FastAPI应用
app = FastAPI(
    title=f"{settings.APP_NAME} API Gateway",
    version=settings.APP_VERSION,
    description="多Agent娱乐搜索系统统一入口网关",
    docs_url="/docs" if settings.APP_DEBUG else None,  # 生产环境关闭Swagger
    redoc_url="/redoc" if settings.APP_DEBUG else None
)

# 配置CORS（跨域资源共享）
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册全局中间件（顺序：先限流 → 再鉴权）
app.middleware("http")(rate_limiter_middleware)
app.middleware("http")(auth_middleware)

# 注册路由（前缀统一为 /api/v1）
app.include_router(search_router, prefix="/api/v1", tags=["搜索接口"])
app.include_router(status_router, prefix="/api/v1", tags=["系统状态"])
app.include_router(async_router, prefix="/api/v1", tags=["异步接口"])

# 全局请求ID生成（用于追踪请求链路）
@app.middleware("http")
async def add_request_id(request: Request, call_next):
    import uuid
    request_id = str(uuid.uuid4())[:8]  # 简化为8位请求ID
    request.state.request_id = request_id
    # 更新日志上下文（添加request_id作为task_id，agent_name设为api_gateway）
    Logger.update_context(task_id=request_id, agent_name="api_gateway")
    response = await call_next(request)
    response.headers["X-Request-ID"] = request_id  # 响应头返回request_id
    return response

# 统一参数校验错误处理
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    logger.error(f"参数校验失败: request_id={request.state.request_id}, errors={exc.errors()}")
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content={
            "code": ErrorCode.PARAM_ERROR.value,
            "message": "参数格式错误",
            "data": {"errors": exc.errors(), "request_id": request.state.request_id}
        }
    )

# 统一异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(
        f"全局异常: request_id={request.state.request_id}, error={str(exc)}",
        exc_info=True
    )
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "code": ErrorCode.SYSTEM_ERROR.value,
            "message": "系统内部错误，请稍后重试",
            "data": {"request_id": request.state.request_id}
        }
    )

# 根路径健康检查
@app.get("/", tags=["基础检查"])
async def root():
    return {
        "code": ErrorCode.SUCCESS.value,
        "message": f"{settings.APP_NAME} API Gateway 运行中",
        "data": {
            "version": settings.APP_VERSION,
            "env": settings.ENVIRONMENT,
            "api_prefix": "/api/v1"
        }
    }

# 启动入口（本地开发用）
if __name__ == "__main__":
    import uvicorn
    logger.info(f"启动API网关: /api/v1，环境: {settings.ENVIRONMENT}")
    uvicorn.run(
        "api_gateway.app:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.APP_DEBUG,  # 开发环境热重载
        log_config=None  # 禁用uvicorn默认日志，使用系统统一日志
    )